<?php
/**
 * weclock 微信消息处理类
 * $Author: tangcheng
 * $time:2015-02-05  
 */
namespace Util;
class WxMenu{
	public $token = '';
	//token
	public $debug = false;
	//是否debug的状态标示，方便我们在调试的时候记录一些中间数据
	public $setFlag = false;
	public $msgtype = 'text';
	//('text','image','location')
	public $msg = array();

	public function __construct($token, $debug) {
		$this -> token = $token;
		$this -> debug = $debug;
	}

	//获得用户发过来的消息（消息内容和消息类型  ）
	public function getMsg() {
		//---------- 接 收 数 据 ---------- //
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

		if ($this -> debug) {
			//$this -> write_log($postStr);
		}
		if (!empty($postStr)) {
			$this -> msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$this -> msgtype = strtolower($this -> msg['MsgType']);
		}
	}

	//回复文本消息
	public function makeText($text = '') {
		$time = time();
		$FuncFlag = $this -> setFlag ? 1 : 0;
		$textTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        <FuncFlag>%s</FuncFlag>
       </xml>";
		$msgType = "text";
		//消息类型
		$resultStr = sprintf($textTpl, $this -> msg['FromUserName'], $this -> msg['ToUserName'], $time, $msgType, $text, $FuncFlag);
		echo $resultStr;

	}

	//回复多客服消息
	function makeService() {
		$xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[transfer_customer_service]]></MsgType>
        </xml>";

		$result = sprintf($xmlTpl, $this -> msg['FromUserName'], $this -> msg['ToUserName'], time());

		echo $result;
	}

	//回复图文消息
	public function makeNews($newsArray) {
		if (!is_array($newsArray)) {
			return;
		}

		$time = time();

		$itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
		$item_str = "";
		foreach ($newsArray as $item) {
			$item_str .= sprintf($itemTpl, $item['title'], $item['desc'], $item['pic_img'], $item['url']);
		}
		$xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[news]]></MsgType>
        <ArticleCount>%s</ArticleCount>
        <Articles>
        $item_str</Articles>
        </xml>";

		$result = sprintf($xmlTpl, $this -> msg['FromUserName'], $this -> msg['ToUserName'], $time, count($newsArray));

		echo $result;
	}

	public function reply($data) {
		if ($this -> debug) {
			//$this -> write_log($data);
		}
		echo $data;
	}

	public function valid($get) {
		$echoStr = $get["echostr"];
		$get_json = json_encode($get);
		//valid signature , option
		if ($this -> checkSignature($get)) {
			//用的框架，echo $echoStr也是对的，但是就是提升token验证失败，没有bom头，编码也是正确的，响应时间也是对的，最后在echo $echoStr前面加一句ob_clean();就好了
			ob_clean();
			echo $echoStr;
			exit ;
		}
	}
	
	//验证签名
	private function checkSignature($get) {
		$signature = $get["signature"];
		$timestamp = $get["timestamp"];
		$nonce = $get["nonce"];
		
		$tmpArr = array($this -> token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode($tmpArr);
		$tmpStr = sha1($tmpStr);
		//$this->logger($tmpStr);
		if ($tmpStr == $signature) {
			return true;
		} else {
			return false;
		}
	}

	

	function logger($log_content) {
		$log_filename = "log.xml";
		if(file_exists($log_filename)){
			$olddata = file_get_contents($log_filename);
			$log_content.=$olddata. "\r\n".$log_content;
		}
		file_put_contents($log_filename, $log_content . "\r\n");
	}

}